package com.example.user.customviewdemo.drawerlayoutmenu;

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.user.customviewdemo.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.Bind;
import butterknife.ButterKnife;

public class DrawerLayoutActivity extends AppCompatActivity implements View.OnClickListener {

    @Bind(R.id.left_drawer)
    ListView leftDrawer;
    @Bind(R.id.right_drawer)
    RelativeLayout rightDrawer;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.textview)
    TextView textview;
    @Bind(R.id.textview1)
    TextView textview1;
    @Bind(R.id.image_view)
    ImageView imageView;


    private ImageView actionImageView;
    private TextView actionTextView;
    private TextView actionPersonalView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_layout);
        ButterKnife.bind(this);

        setHasPermanentMenuKey(false);
        /*
         * ActionBar
         */
        ActionBar actionBar = getSupportActionBar();
        //设置自定义actionbar的view
        actionBar.setCustomView(R.layout.action_bar_layout);
        //设置展示的options为DISPLAY_SHOW_CUSTOM
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        //设置showCustom为true
        actionBar.setDisplayShowCustomEnabled(true);
        //实例化自定义actionbar的view
        actionImageView = (ImageView) actionBar.getCustomView().findViewById(R.id.image_view);
        actionTextView = (TextView) actionBar.getCustomView().findViewById(R.id.textview);
        actionPersonalView = (TextView) actionBar.getCustomView().findViewById(R.id.personal_textview);
        actionPersonalView.setOnClickListener(this);
        actionImageView.setOnClickListener(this);


        /**
         * 左边侧滑菜单
         */
        String[] strs = getResources().getStringArray(R.array.menu_list);
        leftDrawer.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strs));

        /**
         * 主界面按钮添加监听，点击滑出菜单
         */
        textview.setOnClickListener(this);
        textview1.setOnClickListener(this);

        /**
         * drawerLayout添加监听，监听侧滑过程，包括打开，关闭，和侧滑offSet
         * ActionBarDrawerToggle继承了DrawerLayout.DrawerListener
         * 所以可以直接使用
         */
        drawerLayout.addDrawerListener(new ActionBarDrawerToggle(this, drawerLayout, R.string.hello_blank_fragment, R.string.app_name) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                actionTextView.setText("标题");
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
                //设置actionbar中的icon和主界面的imageview旋转
                actionImageView.setRotation(slideOffset*90);
                imageView.setRotation(slideOffset*270);

            }
        });


    }

    /**
     * 通过反射，设置实体menu键可用与否
     * 该方法在onCreate（）中调用
     * @param enable  false:实体键不可用，会在actionbar上显示小点
     *                true：可用，点击menu实体键才会显示menuitem
     */
    public void setHasPermanentMenuKey(boolean enable){
        try {
            ViewConfiguration mconfig = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if(menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(mconfig, enable);
            }
        } catch (Exception ex) {
        }
    }

    /**
     *  android 4.0以后使用AppCompatActivity必须在该方法中调用setIconEnable（），
     *  隐藏的menuitem的icon才会显示
     *  android 4.0以后其他的activity可以再onPrepreOptionMenu()中调用
     *  android 4.0以前可以正常显示overflow中的menuitem的icon
     * @param view
     * @param menu
     * @return
     */
    @Override
    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
        setIconEnable(menu, true);//让在overflow中的menuitem的icon显示
        return super.onPrepareOptionsPanel(view, menu);
    }

    private Menu menu;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;

        int groupId = 1;
        MenuItem item1 = menu.add(groupId, Menu.FIRST + 1, 1, "将第二组item不可见");
        item1.setIcon(R.mipmap.ic_launcher);
        menu.add(groupId, Menu.FIRST + 2, 2, "将第二组item可见");

        menu.add(groupId, Menu.FIRST + 3, 3, "将第二组item不可用");
        MenuItem item4 = menu.add(groupId, Menu.FIRST + 4, 4, "将第二组item可用");
        item4.setIcon(R.mipmap.ic_launcher);
        menu.add(groupId, Menu.FIRST + 5, 5, "将第二组item可单选");
        menu.add(groupId, Menu.FIRST + 6, 6, "将第二组item可多选");

        groupId = 2;
        MenuItem item7 = menu.add(groupId, Menu.FIRST + 7, 7, "menu2_1");
        item7.setIcon(R.mipmap.ic_launcher);
        MenuItem item8 = menu.add(groupId, Menu.FIRST + 8, 8, "menu2_2");
        item8.setIcon(R.mipmap.ic_launcher);

        SubMenu subMenu = menu.addSubMenu(groupId, Menu.FIRST + 9, 9, "sub menu");
        subMenu.add(groupId, Menu.FIRST + 10, 1, "sub1");
        subMenu.add(groupId, Menu.FIRST + 11, 2, "sub2");

        /**
         * 这个监听事件可以对item的点击事件进行拦截，拦截后的item在onOptionsItemSelected()中不会得到执行
         */
        item1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                return true;//返回true为拦截，false不拦截
            }
        });
        return true;
    }


    /**
     * 利用反射机制调用MenuBuilder中的setOptionIconsVisable（），
     * 如果是集成自AppCompatActivity则不行,需要在onPreareOptionPanel（）中调用该方法
     * @param menu   该menu实质为MenuBuilder，该类实现了Menu接口
     * @param enable enable为true时，菜单添加图标有效，enable为false时无效。因为4.0系统之后默认无效
     */
    private void setIconEnable(Menu menu, boolean enable) {
        if (menu != null) {
            try {
                Class clazz = menu.getClass();
                if (clazz.getSimpleName().equals("MenuBuilder")) {
                    Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);

                    //MenuBuilder实现Menu接口，创建菜单时，传进来的menu其实就是MenuBuilder对象(java的多态特征)
                    m.invoke(menu, enable);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case Menu.FIRST + 1:
                menu.setGroupVisible(2, false);
                break;
            case Menu.FIRST + 2:
                menu.setGroupVisible(2, true);
                break;
            case Menu.FIRST + 3:
                menu.setGroupEnabled(2, false);
                break;
            case Menu.FIRST + 4:
                menu.setGroupEnabled(2, true);
                break;
            case Menu.FIRST + 5:
                menu.setGroupCheckable(2, true, true);
                break;
            case Menu.FIRST + 6:
                menu.setGroupCheckable(2, true, false);
                break;
            case Menu.FIRST + 7:
                Toast.makeText(this, "menu2_1", Toast.LENGTH_SHORT).show();
                break;
            case Menu.FIRST + 8:
                Toast.makeText(this, "menu2_2", Toast.LENGTH_SHORT).show();
                break;
            case Menu.FIRST + 10:
                Toast.makeText(this, "sub1", Toast.LENGTH_SHORT).show();
                break;
            case Menu.FIRST + 11:
                Toast.makeText(this, "sub2", Toast.LENGTH_SHORT).show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview:
                drawerLayout.openDrawer(leftDrawer);
                actionTextView.setText("左滑菜单");
                break;
            case R.id.textview1:
                drawerLayout.openDrawer(rightDrawer);
                actionTextView.setText("右滑菜单");
                break;
            case R.id.personal_textview:
                drawerLayout.openDrawer(rightDrawer);
                actionTextView.setText("右滑菜单");
                break;
            case R.id.image_view:
                drawerLayout.openDrawer(leftDrawer);
                actionTextView.setText("左滑菜单");
                break;
        }
    }
}
